package com.vrv.drools.droolsdemo.service;

import com.vrv.drools.droolsdemo.entity.Person;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: TestService
 * @Desc: TODO
 * @author: <Bang>
 * @Date: 2022/08/23 11:32
 * @Version: 1.0
 * @Modified By:
 */
@Service
public class TestService {

    @Resource
    private KieContainer kieContainer;

    @Resource
    private DroolsRuleService droolsRuleService;


//    @PostConstruct
    public void init() {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

                Person person = new Person();
                person.setName("张三");
                person.setAge(30);

                KieSession session = kieContainer.newKieSession();
                session.insert(person);
                int fireAllRules = session.fireAllRules();
                long factCount = session.getFactCount();
                System.out.println(Thread.currentThread().getName() + " 定时任务在执行factCount: " + factCount);
                session.dispose();
            }
        }, 50, 50, TimeUnit.MICROSECONDS);
    }

    public Object test(String name) {
        Person person = new Person();
        person.setName(name);
        person.setAge(30);
        KieSession kieSession = kieContainer.newKieSession();
        kieSession.insert(person);
        int i = kieSession.fireAllRules();
        long factCount = kieSession.getFactCount();
        System.out.println("factCount: " + factCount);
        kieSession.dispose();
        return i;
    }


    public Object test2(String name) {
        Person person = new Person();
        person.setName(name);
        person.setAge(30);

        KieSession session = droolsRuleService.getSession();
        session.insert(person);
        int fireAllRules = session.fireAllRules();
        long factCount = session.getFactCount();
        System.out.println("factCount: " + factCount);
        session.dispose();
        return fireAllRules;
    }
}
